package com.fjwt.gz.proxy.secruity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class AgentAwareAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private GzOrgUserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        AgentAwareAuthenticationToken token = (AgentAwareAuthenticationToken) authentication;

        // 1. 通过机构号和用户名加载用户
        UserDetails userDetails = userDetailsService.loadUserByAgentNoAndUsername(
                token.getAgentNo(),
                token.getPrincipal().toString()
        );

        // 2. 密码验证
        if (!passwordEncoder.matches(token.getCredentials().toString(), userDetails.getPassword())) {
            throw new BadCredentialsException("用户名或密码错误");
        }

        // 3. 返回认证通过的Token
        return new AgentAwareAuthenticationToken(
                token.getAgentNo(),
                userDetails,
                userDetails.getAuthorities()
        );
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return AgentAwareAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
